/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

Ext.QuickTips.init();
var _pageSize = 50;

var fieldName = ['id','orgCode','name','value',];
var fieldLabel = ['ID', '所属单位', '名称', '值'];
var fieldType = [];

var saveServlet = '../../servlet/system/ConstantSave';
var loadServlet = '../../servlet/system/ConstantLoad';
var deleteServlet= '../../servlet/system/ConstantDel';
var dbtable = 't_constant';
var theme = '系统参数表';

var _title = currentOrgName + theme + '管理';

var inputForm = new Ext.FormPanel(
        {
            xtype: 'form',
            id: 'input-form',
            bodyStyle: 'padding:15px;background:transparent',
            frame: true,
            border: false,
            url: saveServlet,            
            items: [{
                    name: fieldName[0],
                    xtype: 'textfield',
                    fieldLabel: fieldLabel[0],
                    hidden: true
                }, {
                    name: fieldName[1],
                    id:'CurrentOrgName',
                    value:currentOrgName,
                    xtype: 'textfield',
                    readOnly:true,
                    fieldLabel: fieldLabel[1],
                    width: 150
                }, {
                    name: fieldName[2],
                    xtype: 'textfield',
                    fieldLabel: fieldLabel[2],
                    width: 150

                }, {
                    name: fieldName[3],
                    xtype: 'textfield',
                    fieldLabel: fieldLabel[3],
                    width: 150
                }
            ],
            buttons: [{
                    text: '保存',
                    iconCls: 'icon-save',
                    handler: function() {                        
                        var submitConfig = {
                            success: function(form, action) {
                                store.reload();
                                //parent.Ext.getCmp('OrganTree').getRootNode().reload();
                      //          parent.Ext.getCmp('OrganTree').getNodeById(currentOrgCode).reload();
                                win.hide();
                            },
                            failure: function(form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('提示', '网络连接失败');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('提示', action.result.msg);
                                }
                            },
                            params: {}
                        };
                        var token1 = new Date().getTime(); 
                        submitConfig.params.token=token;
                        submitConfig.params.token1=token1;
                        if (type === 1)
                            submitConfig.params.cmd = 'create';
                        else {
                            submitConfig.params.id = checkboxSel.getSelected().get("id");
                            submitConfig.params.cmd = 'update';
                        }
                        Ext.getCmp('input-form').getForm().submit(submitConfig);                        
                    }
                }, { 
                    text: '取消',
                    handler: function() {
                        win.hide();
                    }
                }]
        }
);
var win = new Ext.Window({
    layout: 'form',
    width: 340,
    autoHeight: true,
    closeAction: 'hide',
    items: [inputForm]
});
var type = 1;         //判断打开窗口是进行更新，还是新建。1-新建；2-修改
var updated = false;
function addnew() {
    if (win === null) {
        win = new Ext.Window({
            layout: 'form',
            width: 340,
            autoHeight: true,
            closeAction: 'hide',
            items: [inputForm]
        });
    }
    type = 1;
    win.setTitle('增加'+theme);
    //if (updated)
       // Ext.getCmp('addusr-form').getForm().getEl().dom.reset();
    Ext.getCmp('input-form').getForm().reset();
    Ext.getCmp('CurrentOrgName').setValue(currentOrgName);
    win.show();
    //loginForm.form.reset();

    //Ext.getCmp('code').enable();    
}

function update() {
    updated = true;
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("提示", "您还没有选择，需要选择一个记录才能修改");
    }
    else if (checkboxSel.getSelections().length > 1) {
        Ext.Msg.alert("提示", "您选择了多个记录，只能选择一个记录进行修改");
    }
    else {
        if (win === null) {
            win = new Ext.Window({
                layout: 'form',
                width: 340,
                autoHeight: true,
                closeAction: 'hide',
                items: [inputForm]
            });
        }

        //alert(checkboxSel.getSelected().get('code'));
        type = 2;
        Ext.getCmp('input-form').getForm().loadRecord(checkboxSel.getSelected());
        Ext.getCmp('CurrentOrgName').setValue(currentOrgName);
        win.setTitle('修改'+theme);
        win.show();
        //Ext.getDom('win-title').innerHTML='修改监控设备信息';
    }
}

function remove() {
    var token1 = new Date().getTime(); 
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("修改"+theme, "您还没有选择，需要先选择才能删除");
    }
    else {
        Ext.MessageBox.confirm('提示', '确实要删除所选的记录吗?', function(btn) {
            if (btn === 'yes') {
                var records = checkboxSel.getSelections();
                var jsonData = "";
                for (var i = 0, len = records.length; i < len; i++) {
                    var ss = records[i].get("id"); //这里为Grid数据源的Id列
                    if (i === 0)
                        jsonData = jsonData + ss;
                    else
                        jsonData = jsonData + "," + ss;
                }
                var token1 = new Date().getTime();
                var conn = new Ext.data.Connection();
                conn.request({
                    url: deleteServlet, //提交的删除地址
                    params: {token:token,token1:token1,ids: jsonData,token:token,token1:token1},
                    method: 'post',
                    scope: this,
                    callback: function(options, success, response) {
                        if (success) {
                            var messager = Ext.decode(response.responseText);
                            if (messager.success) {
                                Ext.MessageBox.alert("提示", "所选记录成功删除！");
                                store.reload(); //重新load数据   	
                             //   parent.Ext.getCmp('OrganTree').getNodeById(currentOrgCode).reload();
                            }
                            else {
                                Ext.Msg.alert('提示', messager.msg);
                            }

                        } else {
                            Ext.MessageBox.alert("提示", "所选记录删除失败！");
                        }
                    }
                });
            }
        });
    }
}


var checkboxSel = new Ext.grid.CheckboxSelectionModel();
var store;
function buildWindow() {


    store = new Ext.data.JsonStore({
        url: loadServlet,
        root: 'data',
        idProperty: 'id',
        totalProperty: 'count',
        fields: fieldName
    });

    var grid = new Ext.grid.GridPanel({
        title: _title,
        store: store,
        sm: checkboxSel,
        columns: [
            checkboxSel,
            {header: fieldLabel[0], sortable: true, dataIndex: fieldName[0], hidden: true},
            {header: fieldLabel[1], width: 80, sortable: true, dataIndex: fieldName[1],hidden:true},
            {header: fieldLabel[2], width: 200, sortable: true, dataIndex: fieldName[2]},
            {header: fieldLabel[3], width: 150, sortable: true, dataIndex: fieldName[3]}
        ],
        //autoExpandColumn: fieldName[2],
        //renderTo: Ext.getBody(),
        //width: 780,
        //height: 590,
        loadMask: true,
        tbar: new Ext.Toolbar([
            {text: '新增', iconCls: 'icon-add', handler: addnew},
            '-',
            {text: '修改', iconCls: 'icon-edit', handler: update},
            '-',
            {text: '删除', iconCls: 'icon-delete', handler: remove},
            '-',
         //   {text: '用户角色分配', iconCls: 'icon-edit', handler: allocation}
        ]),
        bbar: new Ext.PagingToolbar({
            pageSize: _pageSize,
            store: store,
            displayInfo: true,
            displayMsg: '显示记录：{0} - {1}   总记录：{2}',
            emptyMsg: "目前没有"+theme+'信息'
        })
    });
    //grid.el.center();
    store.load({params: {token:token,start: 0, limit: _pageSize}});

    var applicationUI = new Ext.Viewport({
        layout: "fit",
        items: [
            grid
        ]
    });
}
Ext.onReady(buildWindow);  